home *** CD-ROM | disk | FTP | other *** search
/ NetNews Offline 2 / NetNews Offline Volume 2.iso / news / comp / lang / c-part1 / 7844 < prev    next >
Encoding:
Internet Message Format  |  1996-08-05  |  1.7 KB

  1. Path: anvil.ugrad.cs.ubc.ca!not-for-mail
  2. From: c2a192@ugrad.cs.ubc.ca (Kazimir Kylheku)
  3. Newsgroups: comp.lang.c
  4. Subject: Re: Q: How to assign structures?
  5. Date: 27 Feb 1996 12:51:40 -0800
  6. Organization: Computer Science, University of B.C., Vancouver, B.C., Canada
  7. Message-ID: <4gvqssINNjl8@anvil.ugrad.cs.ubc.ca>
  8. References: <4gsalu$dll@ccshst05.cs.uoguelph.ca>
  9. NNTP-Posting-Host: anvil.ugrad.cs.ubc.ca
  10.  
  11. In article <4gsalu$dll@ccshst05.cs.uoguelph.ca>,
  12. Toby K Hay <thay@uoguelph.ca> wrote:
  13. >I need to assign values to structures in one array from structures in 
  14. >another array - in essence I'm copying the whole structure from one array 
  15. >to the other.  Can I use simple assignment like this:
  16. >
  17. >struct StructName {
  18. >    int     IVal;
  19. >    float    FVal;}
  20. >
  21. >struct StructName Array1[5], Array2[5];
  22. >. . .
  23. >for (i=0;i<5;i++) Array1[i] = Array2[i];
  24. >. . .
  25.  
  26. Yes.
  27.  
  28. >And if not that, can I use memcpy() and sizeof() to do the assignment:
  29.  
  30. Absolutely. memcpy(Array2, Array1, sizeof(Array1)); will do. Don't forget to
  31.  
  32.     #include<string.h>
  33.  
  34. before using memcpy().
  35.  
  36. >for (i=0;i<5;i++) memcpy(&Array2[i],&Array1[i],sizeof(struct StructName));
  37. >Or do I have to assign each element of the structure?
  38.  
  39. No, you don't.
  40.  
  41. Assigning structures, as well as passing them by value and returning them out
  42. of functions was blessed years ago by ANSI.
  43.  
  44. BTW, if you had just _tried_ this instead of asking, you would have found that
  45. it works. But it's good to ask anyway in case your experiment just happens to
  46. takes advantage of a gratuitous non-standard feature implemented only in your
  47. compiler, something which would readily be pointed out by avid contributors to
  48. this newsgroup should it happen. Check the FAQ as well and have your K&R2 by
  49. your side always.
  50. -- 
  51.  
  52.